<template>
  <div class="pifajia">
    <div class="top">
      <div class="name">{{ CSdata.sName }}</div>
      <a
        href="javascript:;"
        :class="{ check: ischeck == 1 }"
        @click="$store.dispatch('saveisCheck', 1)"
        >课件资料</a
      >
      <a
        href="javascript:;"
        :class="{ check: ischeck == 2 }"
        @click="getExample"
        v-if="
          $store.state.CSdata.sKey === 20 ||
            $store.state.CSdata.sKey === 21 ||
            $store.state.CSdata.sKey === 22 ||
            $store.state.CSdata.sKey === 23 ||
            $store.state.CSdata.sKey === 24 ||
            $store.state.CSdata.sKey === 25 ||
            $store.state.CSdata.sKey === 26 ||
            $store.state.CSdata.sKey === 33 ||
            $store.state.CSdata.sKey === 34
        "
        >算例展示</a
      >
    </div>
    <div class="bottom" v-if="ischeck == 1">
      <div class="download">
        {{ CSdata.cName + '-' + CSdata.sName }}
        <a :href="downloadUrl" target="_blank">点击下载文件</a>
      </div>
      <div class="swiper">
        <swiper :options="swiperOption" ref="mySwiper">
          <swiper-slide v-for="(item, index) in banners" :key="index">
            <img :src="item" alt="" />
            <div class="yanshi" @click="playAnimation">
              <img src="/imgs/click.png" alt="" />
              <p>点击查看演示</p>
            </div>
          </swiper-slide>
          <div class="swiper-pagination" slot="pagination"></div>
          <div class="swiper-button-prev" slot="button-prev"></div>
          <div class="swiper-button-next" slot="button-next"></div>
          <div class="swiper-scrollbar" slot="scrollbar"></div>
        </swiper>
      </div>
      <div class="contain">
        <div class="discuss">
          <div class="title">
            <h2>课堂讨论区</h2>
          </div>
        </div>
        <CommentBox
          :userInfo="userInfo"
          :reply-info="replyInfo"
          @submit-box="submitBox"
          @upload-img="upload"
          :showCancle="showCancle"
        ></CommentBox>
        <CommentList
          :comments="comments"
          @delete-comment="deleteComment"
          @change-state="changeState"
          @like="like"
        ></CommentList>
      </div>
    </div>
    <div class="example" v-if="ischeck == 2">
      <pifajia v-if="$store.state.CSdata.sKey === 20"></pifajia>
      <huigou v-if="$store.state.CSdata.sKey === 21"></huigou>
      <shouyigongxiang v-if="$store.state.CSdata.sKey === 22"></shouyigongxiang>
      <shuliangrouxin v-if="$store.state.CSdata.sKey === 23"></shuliangrouxin>
      <xiaoshouzhekou v-if="$store.state.CSdata.sKey === 24"></xiaoshouzhekou>
      <shuliangzhekou v-if="$store.state.CSdata.sKey === 25"></shuliangzhekou>
      <paimaishang v-if="$store.state.CSdata.sKey === 33"></paimaishang>
      <paimaixia v-if="$store.state.CSdata.sKey === 34"></paimaixia>
      <jingtaiboyi v-if="$store.state.CSdata.sKey === 26"></jingtaiboyi>
    </div>
    <!-- 动画弹框 -->
    <a-modal :width="1000" v-model="visible" title="演示" @ok="visible = false">
      <video-player
        ref="videoPlayer"
        class="video-player vjs-custom-skin"
        :playsinline="true"
        :options="playerOptions"
        @play="onPlayerPlay($event)"
        @pause="onPlayerPause($event)"
      />
    </a-modal>
  </div>
</template>
<script>
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
import CommentList from '../components/CommentList'
import CommentBox from '../components/CommentBox'
import { mapMutations } from 'vuex'
// 算例
import Pifajia from '../components/qiyue-example/pifajia.vue'
import Huigou from '../components/qiyue-example/huigou.vue'
import Shouyigongxiang from '../components/qiyue-example/shouyigongxiang.vue'
import Shuliangrouxin from '../components/qiyue-example/shuliangrouxin.vue'
import Xiaoshouzhekou from '../components/qiyue-example/xiaoshouzhekou.vue'
import Shuliangzhekou from '../components/qiyue-example/shuliangzhekou.vue'
import Paimaishang from '../components/boyilun-example/paimaishang.vue'
import Paimaixia from '../components/boyilun-example/paimaixia.vue'
import Jingtaiboyi from '../components/boyi-example/jingtaiboyi'

// 算例
import { URL } from '../api/api.js'
export default {
  name: 'contentTem',
  components: {
    swiper,
    swiperSlide,
    CommentList,
    CommentBox,
    Pifajia,
    Huigou,
    Shouyigongxiang,
    Shuliangrouxin,
    Xiaoshouzhekou,
    Shuliangzhekou,
    Paimaishang,
    Paimaixia,
    Jingtaiboyi,
  },
  data() {
    return {
      URL: URL,
      swiperOption: {
        // autoplay: {
        // delay: 100000,
        // stopOnLastSlide: false,
        // disableOnInteraction: false
        // },
        // // 显示分页
        pagination: {
          el: '.swiper-pagination',
          clickable: true, //允许分页点击跳转
        },
        // // 设置点击箭头
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        effect: 'slide',
        scrollbar: {
          el: '.swiper-scrollbar',
          hide: true,
        },
      },
      banners: [],
      setTree: [],
      page_numbers: 0,
      downloadUrl: '', //下载ppt地址
      // git评论

      showCancle: false,
      submitting: false,
      value: '',
      userInfo: {
        uid: 'uid000001',
        userName: '张三',
        avatar:
          'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      },
      replyInfo: {
        uid: '',
        blogUid: 'uid000003',
        replyUserUid: 'uid000004',
        replyUid: 0,
        avatar:
          'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
      },
      // comments: [
      //     {
      //         uid: 'uid000',
      //         userName: "陌溪",
      //         avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
      //         content: '我是一级评论',
      //         reply: [
      //             {
      //                 uid: 'uid001',
      //                 userName: "陌溪",
      //                 avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
      //                 content: '我是二级评论',
      //                 reply: [
      //                     {
      //                         uid: 'uid002',
      //                         userName: "陌溪",
      //                         avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
      //                         content: '我是三级评论',
      //                         reply: []
      //                     }
      //                 ]
      //             }
      //         ]
      //     },
      //     {
      //         uid: 'uid004',
      //         userName: "陌溪",
      //         avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
      //         content: '我是一级评论',
      //         reply: [
      //         ]
      //     },
      // ],
      comments: [], //评论列表
      imgList: [], //图片列表
      visible: false, //动画弹框可见性
      // 视频
      playerOptions: {
        // playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'video/mp4', // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            //'https://cn-gdfs-dx-bcache-05.bilivideo.com/upgcxcode/64/12/349391264/349391264-1-208.mp4?e=ig8euxZM2rNcNbhVnwdVhwdlhzd3hwdVhoNvNC8BqJIzNbfq9rVEuxTEnE8L5F6VnEsSTx0vkX8fqJeYTj_lta53NCM=&uipk=5&nbs=1&deadline=1625339211&gen=playurlv2&os=bcache&oi=3073951711&trid=00000237ef0e97a84722a4e472e9ce3be2e8T&platform=html5&upsig=ec0e2a40be6dc7899862415d18251108&uparams=e,uipk,nbs,deadline,gen,os,oi,trid,platform&cdnid=60905&mid=580104086&bvc=vod&orderid=0,1&logo=80000000'// url地址
            src: require('../assets/video/蜜雪冰城.mp4'),
          },
        ],
        hls: true,
        poster:
          'https://i1.hdslb.com/bfs/archive/1799c28e4ded092125dea14c752b463b8d59420a.jpg', // 你的封面地址
        width: document.documentElement.clientWidth, // 播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, // 全屏按钮
        },
      },
    }
  },
  mounted() {
    this.axios.defaults.headers.common[
      'Authorization'
    ] = window.sessionStorage.getItem('token')
    ;(async () => {
      for (let i = 0; i < this.$store.state.CSdata.pageNumbers; i++) {
        await this.axios
          .post('/course/get_sectionfile_page/', {
            key: this.$store.state.CSdata.sKey,
            page_number: i + 1,
          })
          .then(res => {
            // console.log(res)
            let url = this.URL + '/' + res.url
            this.banners.push(url)
          })
      }
    })()

    this.download() //获取下载地址
    this.setCommentList(this.comments) //评论
    // 获取评论
    this.getComments()
    //登录
    setInterval(() => {
      if (window.sessionStorage.getItem('account')) {
        this.login()
      }
    }, 60000)
  },
  methods: {
    login() {
      this.axios
        .post('/user/login/', {
          username: window.sessionStorage.getItem('account'),
          password: window.sessionStorage.getItem('password'),
        })
        .then(res => {
          window.sessionStorage.setItem('token', 'JWT ' + res.token)
        })
    },
    download() {
      this.axios
        .post('/course/download_file/', {
          key: this.$store.state.CSdata.sKey,
        })
        .then(res => {
          this.downloadUrl = this.URL + '/' + res
        })
    },
    //拿到vuex中的写的两个方法
    ...mapMutations(['setCommentList', 'increment']),
    submitBox(e) {
      var comments = this.$store.state.commentList
      e.uid = this.$store.state.id
      comments.push(e)
      this.$store.commit('setCommentList', comments)
      this.$store.commit('increment')

      console.log(this.$store.state.userKey)
      console.log(e.content)
      console.log(this.CSdata.sKey)
      const formData = new FormData()
      formData.append('user_key', this.$store.state.userKey)
      formData.append('content', e.content)
      formData.append('section_key', this.CSdata.sKey)
      console.log(this.imgList)
      for (var i = 0; i < this.imgList.length; i++) {
        formData.append('file', this.imgList[i])
      }
      this.axios({
        method: 'post',
        url: '/course/add_note/',
        data: formData,
      })
      //获取评论
      setTimeout(() => {
        this.comments = []
        this.getComments()
      }, 100)
    },
    //上面评论的
    // 获取评论
    getComments() {
      this.axios
        .post('/course/query_note/', {
          section_key: this.CSdata.sKey,
        })
        .then(res => {
          console.log(res)
          res.forEach(element => {
            const obj = {}
            obj.uid = element.user_key
            obj.userName = element.username
            obj.key = element.key
            obj.sectionKey = element.section_key
            obj.content = element.content
            obj.pictures = element.pictures
            obj.isPublic = element.is_public
            obj.likeNum = element.likes_number
            obj.avatar =
              'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
            this.comments.push(obj)
          })
        })
    },
    // 选择图片
    upload(imgList) {
      this.imgList = imgList
    },
    //删除评论
    deleteComment(key, sKey) {
      this.axios.post('/course/delete_note/', {
        note_key: key,
      })
      const arr = this.comments.filter(item => {
        return !(item.key === key)
      })
      this.comments = arr
    },
    // 改变评论状态
    changeState(key, isPublic) {
      this.axios.post('/course/change_note_status/', {
        note_key: key,
        is_public: isPublic === 1 ? 0 : 1,
      })
      this.comments = []
      this.getComments()
    },
    // 点赞
    like(uid, key) {
      console.log(this.$store.state.userKey)
      this.axios
        .post('/course/vote_note/', {
          user_key: this.$store.state.userKey,
          note_key: key,
        })
        .then(() => {
          this.comments = []
          this.getComments()
        })
    },
    // 获取算例
    getExample() {
      this.axios
        .post('/course/query_example/', {
          section_key: this.$store.state.CSdata.sKey,
        })
        .then(res => {
          this.$store.dispatch('saveExampleKey', res[0].key)
          this.$store.dispatch('saveExampleData', res)
          this.$store.dispatch('saveisCheck', 2)
        })
    },
    // 弹框播放动画
    playAnimation() {
      this.visible = true
    },
  },

  computed: {
    CSdata() {
      return this.$store.state.CSdata
    },
    ischeck() {
      return this.$store.state.isCheck
    },
    // 视频
    player() {
      return this.$refs.videoPlayer.player //自定义播放
    },
  },
  watch: {
    CSdata() {
      //获取PPT图
      this.banners = []
      this.axios.defaults.headers.common[
        'Authorization'
      ] = window.sessionStorage.getItem('token')
      ;(async () => {
        for (let i = 0; i < this.$store.state.CSdata.pageNumbers; i++) {
          await this.axios
            .post('/course/get_sectionfile_page/', {
              key: this.$store.state.CSdata.sKey,
              page_number: i + 1,
            })
            .then(res => {
              // console.log(res)
              let url = this.URL + '/' + res.url
              this.banners.push(url)
            })
        }
      })()

      this.download() //获取下载地址
      // 获取评论
      this.comments = []
      this.getComments()
    },
  },
}
</script>

<style lang="scss">
.pifajia {
  display: flex;
  flex-direction: column;
  .top {
    width: 100%;
    height: 93px;
    background-color: #fff;
    margin-bottom: 10px;
    .name {
      height: 68px;
      font-size: 20px;
      padding: 18px;
    }
    a {
      margin-left: 65px;
      padding-bottom: 5px;
      color: #000;
      &.check {
        color: #1990fe;
        border-bottom: 2px solid #1990fe;
      }
    }
  }
  .bottom {
    // height: calc(100vh - 65px - 103px);
    background-color: rgba(204, 204, 204, 0.096);
    .download {
      width: 1260px;
      background-color: #fff;
      margin-top: 5px;
      padding-top: 22px;
      height: 50px;
      font-size: 14px;
      padding-left: 39px;
      a {
        font-size: 14px;
        padding-left: 39px;
      }
    }
    .swiper {
      position: relative;
      width: 1000px;
      height: 562px;
      background-color: #fff;
      margin: 0 auto;
      img {
        width: 1000px;
        height: 600px;
        background-color: skyblue;
      }
      .yanshi {
        position: absolute;
        top: 36px;
        right: 36px;
        width: 166px;
        height: 41px;
        line-height: 41px;
        opacity: 0.7;
        background-color: rgba(17, 17, 17, 100);
        border-radius: 5px 5px 5px 5px;
        font-size: 16px;
        text-align: center;
        color: #fff;
        cursor: pointer;
        img {
          display: inline-block;
          width: 24px;
          height: 24px;
          position: absolute;
          top: 8px;
          left: 10px;
          background-color: rgba(17, 17, 17, 100);
          margin-right: 10px;
        }
        p {
          margin-left: 25px;
        }
      }
    }
  }
  .contain {
    width: 1000px;
    margin: 0 auto;
    .discuss {
      margin-top: 100px;
      .title {
        border-bottom: 1px solid skyblue;
      }
    }
  }
}
</style>
